import axios from 'axios'
import crypto from 'crypto'

// 币安API配置
const BINANCE_API_KEY = process.env.BINANCE_API_KEY
const BINANCE_API_SECRET = process.env.BINANCE_API_SECRET
const BINANCE_TESTNET = process.env.BINANCE_TESTNET === 'true'
const BINANCE_BASE_URL = BINANCE_TESTNET
  ? 'https://testnet.binance.vision'
  : 'https://api.binance.com'

// 创建签名
function createSignature(queryString) {
  return crypto
    .createHmac('sha256', BINANCE_API_SECRET)
    .update(queryString)
    .digest('hex')
}

// 发送API请求
async function binanceRequest(method, endpoint, params = {}, signed = false) {
  if (!BINANCE_API_KEY || !BINANCE_API_SECRET) {
    throw new Error('币安API密钥未配置')
  }

  const url = `${BINANCE_BASE_URL}${endpoint}`
  const headers = {
    'X-MBX-APIKEY': BINANCE_API_KEY
  }

  let queryString = ''
  if (method === 'GET') {
    queryString = new URLSearchParams(params).toString()
  }

  if (signed) {
    const timestamp = Date.now()
    params.timestamp = timestamp
    queryString = new URLSearchParams(params).toString()
    const signature = createSignature(queryString)
    queryString += `&signature=${signature}`
  }

  try {
    const response = await axios({
      method,
      url: signed ? `${url}?${queryString}` : url,
      headers,
      data: method === 'POST' ? params : undefined,
      params: method === 'GET' && !signed ? params : undefined
    })
    return response.data
  } catch (error) {
    console.error('币安API请求失败:', error.response?.data || error.message)
    throw error
  }
}

// 初始化币安客户端
export function initBinanceClient() {
  if (!BINANCE_API_KEY || !BINANCE_API_SECRET) {
    console.warn('币安API密钥未配置，部分功能将不可用')
    return null
  }
  return {
    getAccountInfo,
    getBalance,
    withdraw,
    getDepositAddress,
    getDepositHistory
  }
}

// 获取账户信息
export async function getAccountInfo() {
  return binanceRequest('GET', '/api/v3/account', {}, true)
}

// 获取余额
export async function getBalance(asset = 'USDT') {
  const account = await getAccountInfo()
  const balance = account.balances.find(b => b.asset === asset)
  return balance ? parseFloat(balance.free) : 0
}

// 提现
export async function withdraw({
  asset = 'USDT',
  address,
  amount,
  network = 'ETH',
  addressTag,
  name
}) {
  const params = {
    asset,
    address,
    amount: amount.toString(),
    network,
    ...(addressTag && { addressTag }),
    ...(name && { name })
  }

  return binanceRequest('POST', '/sapi/v1/capital/withdraw/apply', params, true)
}

// 获取充值地址
export async function getDepositAddress(coin = 'USDT', network = 'ETH') {
  return binanceRequest('GET', '/sapi/v1/capital/deposit/address', {
    coin,
    network
  }, true)
}

// 获取充值历史
export async function getDepositHistory(coin = 'USDT', limit = 100) {
  return binanceRequest('GET', '/sapi/v1/capital/deposit/hisrec', {
    coin,
    limit
  }, true)
}

// 获取提现历史
export async function getWithdrawHistory(coin = 'USDT', limit = 100) {
  return binanceRequest('GET', '/sapi/v1/capital/withdraw/history', {
    coin,
    limit
  }, true)
}

export default {
  initBinanceClient,
  getAccountInfo,
  getBalance,
  withdraw,
  getDepositAddress,
  getDepositHistory,
  getWithdrawHistory
}

